<template>
  <div class="rich-text-container">
    <h2>富文本编辑器</h2>
    <div class="editor-container">
      <div id="quill-toolbar">
        <span class="ql-formats">
          <button class="ql-bold"></button>
          <button class="ql-italic"></button>
          <button class="ql-underline"></button>
          <button class="ql-strike"></button>
        </span>
        <span class="ql-formats">
          <button class="ql-script" value="sub"></button>
          <button class="ql-script" value="super"></button>
        </span>
        <span class="ql-formats">
          <button class="ql-header" value="1"></button>
          <button class="ql-header" value="2"></button>
          <button class="ql-blockquote"></button>
          <button class="ql-code-block"></button>
        </span>
        <span class="ql-formats">
          <button class="ql-list" value="ordered"></button>
          <button class="ql-list" value="bullet"></button>
          <button class="ql-indent" value="-1"></button>
          <button class="ql-indent" value="+1"></button>
        </span>
        <span class="ql-formats">
          <button class="ql-link"></button>
          <button class="ql-image"></button>
        </span>
        <span class="ql-formats">
          <button class="ql-clean"></button>
        </span>
      </div>
      <div class="editor"></div>
    </div>

    <div class="content-preview" v-if="content">
      <h3>内容预览</h3>
      <div v-html="content"></div>
    </div>
    
    <div class="actions">
      <el-button type="primary" @click="getContent">获取内容</el-button>
      <el-button type="success" @click="saveContent">保存内容</el-button>
      <el-button @click="clearContent">清空内容</el-button>
      <el-button type="info" @click="loadSavedContent">加载保存的内容</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const content = ref('')
const STORAGE_KEY = 'quill_editor_content'
let quill = null

// 图片上传处理
const handleImageUpload = () => {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')
  input.click()
  
  input.onchange = () => {
    const file = input.files[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const range = quill.getSelection()
          if (range) {
            quill.insertEmbed(range.index, 'image', e.target.result)
            ElMessage.success('图片上传成功')
          } else {
            quill.insertEmbed(0, 'image', e.target.result)
            ElMessage.success('图片已添加到文档开头')
          }
        } catch (error) {
          console.error('插入图片错误:', error)
          ElMessage.error('插入图片失败')
        }
      }
      reader.readAsDataURL(file)
    }
  }
}

onMounted(async () => {
  // 确保在DOM完全渲染后再初始化Quill
  await nextTick()
  
  // 动态导入Quill以避免SSR问题
  try {
    const Quill = (await import('quill')).default
    await import('quill/dist/quill.snow.css')
    
    // 自定义图片处理器
    const ImageBlot = Quill.import('formats/image')
    class CustomImageBlot extends ImageBlot {
      static create(value) {
        const node = super.create(value)
        node.setAttribute('style', 'max-width: 100%;')
        return node
      }
    }
    Quill.register('formats/image', CustomImageBlot, true)
    
    // 初始化Quill编辑器，使用自定义工具栏
    quill = new Quill('.editor', {
      modules: {
        toolbar: {
          container: '#quill-toolbar',
          handlers: {
            image: handleImageUpload
          }
        }
      },
      theme: 'snow',
      placeholder: '请输入内容...'
    })
    
    // 检查是否有保存的内容
    const savedContent = localStorage.getItem(STORAGE_KEY)
    if (savedContent) {
      try {
        quill.clipboard.dangerouslyPasteHTML(savedContent)
        ElMessage.info('已加载上次保存的内容')
      } catch (error) {
        console.error('加载保存内容失败:', error)
        quill.setText('欢迎使用富文本编辑器！')
      }
    } else {
      // 添加一些示例内容
      quill.setText('欢迎使用富文本编辑器！')
    }
    
    // 添加编辑器变化事件监听
    quill.on('text-change', () => {
      // 可以在这里添加自动保存功能
    })
    
    // 确保只有一个工具栏
    const toolbars = document.querySelectorAll('.ql-toolbar.ql-snow')
    if (toolbars.length > 1) {
      for (let i = 1; i < toolbars.length; i++) {
        toolbars[i].remove()
      }
    }
  } catch (error) {
    console.error('初始化Quill编辑器失败:', error)
    ElMessage.error('初始化编辑器失败')
  }
})

// 获取编辑器内容
const getContent = () => {
  if (!quill) return
  const editorContent = quill.root.innerHTML
  content.value = editorContent
}

// 保存内容到本地存储
const saveContent = () => {
  if (!quill) return
  const editorContent = quill.root.innerHTML
  localStorage.setItem(STORAGE_KEY, editorContent)
  ElMessage.success('内容已保存')
}

// 加载保存的内容
const loadSavedContent = () => {
  if (!quill) return
  const savedContent = localStorage.getItem(STORAGE_KEY)
  if (savedContent) {
    quill.clipboard.dangerouslyPasteHTML(savedContent)
    ElMessage.success('已加载保存的内容')
  } else {
    ElMessage.warning('没有找到保存的内容')
  }
}

// 清空编辑器内容
const clearContent = () => {
  if (!quill) return
  ElMessageBox.confirm('确定要清空编辑器内容吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    quill.setText('')
    content.value = ''
    ElMessage.success('内容已清空')
  }).catch(() => {
    // 取消操作
  })
}

onUnmounted(() => {
  // 清理资源
  quill = null
})
</script>

<style>
.rich-text-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 20px;
  overflow: hidden;
}

/* 自定义工具栏样式 */
#quill-toolbar {
  border-bottom: 1px solid #dcdfe6;
  padding: 12px;
  background-color: #f5f7fa;
}

/* 隐藏所有自动生成的工具栏 */
.ql-toolbar.ql-snow:not(#quill-toolbar) {
  display: none !important;
}

/* 增大工具栏按钮尺寸 */
.ql-toolbar.ql-snow .ql-formats {
  margin-right: 15px;
}

.ql-toolbar.ql-snow button {
  width: 32px;
  height: 32px;
}

.ql-toolbar.ql-snow button svg {
  width: 20px;
  height: 20px;
}

.editor {
  height: 500px;
  font-size: 18px;
  background-color: white;
}

.content-preview {
  margin-top: 30px;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 15px;
}

/* 确保编辑器区域显示正确 */
.ql-container.ql-snow {
  border: none !important;
}

.ql-editor {
  min-height: 450px;
  font-size: 18px;
  line-height: 1.6;
  padding: 20px;
}

.ql-editor img {
  max-width: 100%;
}

/* 处理移动设备响应式 */
@media screen and (max-width: 768px) {
  .actions {
    flex-wrap: wrap;
  }
  
  .editor {
    height: 350px;
  }
  
  .rich-text-container {
    padding: 10px;
  }
}
</style> 